package com.example.administrator.caigou51.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ab.util.AbFileUtil;
import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.bean.CategoryBean;
import com.example.administrator.caigou51.bean.CheckOrderBean;
import com.example.administrator.caigou51.bean.MainDataBean;
import com.example.administrator.caigou51.bean.RegionBean;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.cardView.StoreManagerCardView;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.example.administrator.caigou51.util.CameraUtil;
import com.example.administrator.caigou51.util.ImageDealTheard;
import com.example.administrator.caigou51.util.ImageUtil;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.util.YanZhengUtil;
import com.example.administrator.caigou51.widget.EditDialog.EditDialog;
import com.example.administrator.caigou51.widget.EditDialog.EditDialogAction;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;
import com.example.administrator.caigou51.widget.wheel.SelectAreaPopupWindow;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by Administrator on 2016/9/5/005.
 */
public class ZhiZhiCheckActivity  extends GBaseActivity  implements SelectAreaPopupWindow.InterFaceGetData{
    private TextView textViewWXTS;
    private TextView textViewSHSB;
    private EditText editTextUserName;
    private EditText editTextTel;
    private EditText editTextCompanyName;
    private LinearLayout linearLayoutChooseArea;
    private TextView textChooseAddress;
    private EditText editTextAddressDetail;
    private ImageView imageView1;
    private ImageView imageViewDel1;
    private ImageView imageView2;
    private ImageView imageViewDel2;
    private ImageView imageView3;
    private ImageView imageViewDel3;
    private TextView textViewGoOnAdd,textViewPleaseTips;
    private TextView textViewSumit;
    private CameraUtil cameraUtil;
    private EditDialog editDialog;
    private boolean clickImageView1=false;
    private boolean clickImageView2=false;
    private boolean clickImageView3=false;
    private String file1="";
    private String file2="";
    private String file3="";
    private SelectAreaPopupWindow selectAreaPopupWindow;
    private RegionBean  regionBean;
    private String areaId="";
    public static String TagAddressEntity="TagAddressEntity";
    com.example.administrator.caigou51.bean.CheckOrderBean.AddressEntity addressEntity;
    private String addressID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_zhizhi_check);
        findViewByIds();
        initDatas();
        fillArrayInListView();
        TaskGetRegionBean(false);
    }

    private void findViewByIds() {
        textViewWXTS = (TextView) findViewById(R.id.textViewWXTS);
        textViewSHSB = (TextView) findViewById(R.id.textViewSHSB);
        textViewPleaseTips= (TextView) findViewById(R.id.textViewPleaseTips);
        linearLayoutChooseArea = (LinearLayout) findViewById(R.id.linearLayoutChooseArea);
        imageViewDel1= (ImageView) findViewById(R.id.imageViewDel1);
        imageViewDel2= (ImageView) findViewById(R.id.imageViewDel2);
        imageViewDel3= (ImageView) findViewById(R.id.imageViewDel3);
        imageView1 = (ImageView) findViewById(R.id.imageView1);imageView1.setOnClickListener(this);
        imageView2 = (ImageView) findViewById(R.id.imageView2);imageView2.setOnClickListener(this);
        imageView3 = (ImageView) findViewById(R.id.imageView3);imageView3.setOnClickListener(this);
        imageViewDel1.setOnClickListener(this);imageViewDel1.setVisibility(View.GONE);
        imageViewDel2.setOnClickListener(this);imageViewDel2.setVisibility(View.GONE);
        imageViewDel3.setOnClickListener(this);imageViewDel3.setVisibility(View.GONE);
        textViewGoOnAdd = (TextView) findViewById(R.id.textViewGoOnAdd);textViewGoOnAdd.setOnClickListener(this);
        textViewSumit = (TextView) findViewById(R.id.textViewSumit);textViewSumit.setOnClickListener(this);

        editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        editTextTel = (EditText) findViewById(R.id.editTextTel);
        editTextCompanyName = (EditText) findViewById(R.id.editTextCompanyName);
        textChooseAddress = (TextView) findViewById(R.id.textChooseAddress);textChooseAddress.setOnClickListener(this);
        editTextAddressDetail = (EditText) findViewById(R.id.editTextAddressDetail);
    }

    private void initDatas() {
        setTopTitle("资质认证");
        cameraUtil = new CameraUtil(getActivity());
        if (getIntent().getSerializableExtra(TagAddressEntity)!=null)
        {

            addressEntity= (CheckOrderBean.AddressEntity) getIntent().getSerializableExtra(TagAddressEntity);
            addressID=addressEntity.getItemid();
            editTextUserName.setText(addressEntity.getTruename());editTextUserName.setEnabled(false);
            editTextTel.setText(addressEntity.getMobile());editTextTel.setEnabled(false);
            editTextCompanyName.setText(addressEntity.getCompany_name());editTextCompanyName.setEnabled(false);
            textChooseAddress.setText(addressEntity.getRegion_name());
            editTextAddressDetail.setText(addressEntity.getAddress());
            imageView2.setPadding(0,0,0,0);
            imageView1.setPadding(0,0,0,0);
            imageView3.setPadding(0,0,0,0);
            file1=addressEntity.getCharter();
            file2=addressEntity.getGsp();
            file3=addressEntity.getLicense();
            areaId=addressEntity.getAreaid();
            App.displayImageHttpOrFile(addressEntity.getCharter(),imageView1,ImageUtil.OptionsActivity());
            App.displayImageHttpOrFile(addressEntity.getGsp(),imageView2,ImageUtil.OptionsActivity());
            App.displayImageHttpOrFile(addressEntity.getLicense(),imageView3,ImageUtil.OptionsActivity());
            textViewSHSB.setVisibility(View.VISIBLE);
            textViewWXTS.setVisibility(View.GONE);
            textViewSumit.setVisibility(View.GONE);
            textViewPleaseTips.setText("基本信息");
            if (addressEntity.getIs_verified().equals(StoreManagerCardView.stateShenKeIng))
            {

                textViewSHSB.setText("请耐心等候，店铺审核中");
                textViewSHSB.setTextColor(getResources().getColor(R.color.color_1ca146));
            }else if  (addressEntity.getIs_verified().equals(StoreManagerCardView.stateRenZheng))
            {
                textViewSHSB.setText("恭喜，店铺已成功认证");
                textViewSHSB.setTextColor(getResources().getColor(R.color.color_1ca146));
            }else if  (addressEntity.getIs_verified().equals(StoreManagerCardView.stateShenKeFail))
            {
                textViewSHSB.setTextColor(getResources().getColor(R.color.color_ee4528));
                textViewSHSB.setText("店铺审核失败，请重新上传");
                textViewSumit.setVisibility(View.VISIBLE);
                editTextUserName.setEnabled(true);
                editTextTel.setEnabled(true);
                editTextCompanyName.setEnabled(true);
            }
        }
    }
    private void fillArrayInListView() {
    }
    private void TaskGetRegionBean(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY(null, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_RegionList, Constant.Action.Action_RegionList, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_RegionList), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                       //  regionBean

                       List<RegionBean.DataEntity> list   = JSON.parseArray(result.getData().toString(), RegionBean.DataEntity.class);
                        if (regionBean==null)
                        {
                            regionBean=new RegionBean();
                            regionBean.setData(list);
                        }else
                        {
                            regionBean.setData(list);
                        }
                        if (selectAreaPopupWindow == null) {
                            selectAreaPopupWindow = new SelectAreaPopupWindow(ZhiZhiCheckActivity.this, regionBean, ZhiZhiCheckActivity.this);
                        }
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
    // put(Action.Action_SumitZhiZhi, new String[]{"userid","session_id","company_name","areaid","address"});
    private void TaskSumit(final boolean isloadmore) {

        String companyName= editTextCompanyName.getText().toString();
        String detailAddress = editTextAddressDetail.getText().toString();
        String consignee= editTextUserName.getText().toString();
        String mobile = editTextTel.getText().toString();



        if (TextUtils.isEmpty(companyName) || TextUtils.isEmpty(detailAddress) || TextUtils.isEmpty(consignee) || TextUtils.isEmpty(mobile) || TextUtils.isEmpty(areaId)
       || TextUtils.isEmpty(file1) || TextUtils.isEmpty(file2) || TextUtils.isEmpty(file3))
        {
            ToastUtil.showToast("请把信息填写完整");
            return;
        }
        if ( !TextUtils.isEmpty(mobile) && !YanZhengUtil.isMobileNO(mobile)) {
            ToastUtil.showToast("请正确填写手机号码");
            return;
        }
        //areaId
        java.util.HashMap<String, File> fileHashMap =new HashMap<>();
        fileHashMap.put("charter",new File(file1));
        fileHashMap.put("gsp",new File(file2));
        fileHashMap.put("license",new File(file3));
        RequestServerManager.getInstanceDIY().handleMethodDIY(this, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_SumitZhiZhi, Constant.Action.Action_SumitZhiZhi, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_SumitZhiZhi,fileHashMap,null,App.getUserBean().getUserid(),App.getUserBean().getSession_id()
                        ,companyName,areaId,detailAddress,consignee,mobile), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        //  regionBean

                         ToastUtil.showToast("提交成功");
                            finish();
                        Intent intent=new Intent(ZhiZhiCheckActivity.this,StoreManagerActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }

    private void TaskEdit(final boolean isloadmore) {

        String companyName= editTextCompanyName.getText().toString();
        String detailAddress = editTextAddressDetail.getText().toString();
        String consignee= editTextUserName.getText().toString();
        String mobile = editTextTel.getText().toString();



        if (TextUtils.isEmpty(companyName) || TextUtils.isEmpty(detailAddress) || TextUtils.isEmpty(consignee) || TextUtils.isEmpty(mobile)
                || TextUtils.isEmpty(file1) || TextUtils.isEmpty(file2) || TextUtils.isEmpty(file3))
        {
            ToastUtil.showToast("请把信息填写完整");
            return;
        }
        if ( !TextUtils.isEmpty(mobile) && !YanZhengUtil.isMobileNO(mobile)) {
            ToastUtil.showToast("请正确填写手机号码");
            return;
        }

        //areaId
        java.util.HashMap<String, File> fileHashMap =new HashMap<>();
        if (!TextUtils.isEmpty(file1) && !file1.contains("http"))
        fileHashMap.put("charter",new File(file1));
        if (!TextUtils.isEmpty(file2) && !file2.contains("http"))
        fileHashMap.put("gsp",new File(file2));
        if (!TextUtils.isEmpty(file3) && !file3.contains("http"))
        fileHashMap.put("license",new File(file3));
        RequestServerManager.getInstanceDIY().handleMethodDIY(this, null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_EditZhiZhi, Constant.Action.Action_EditZhiZhi, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_EditZhiZhi,fileHashMap,null,App.getUserBean().getUserid(),App.getUserBean().getSession_id()
                                ,companyName,areaId,detailAddress,consignee,mobile,addressID), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        // JSONObject jsonObject = (JSONObject) result.getData();
                        //  regionBean

                        ToastUtil.showToast("提交成功");
                        finish();
                        Intent intent=new Intent(ZhiZhiCheckActivity.this,StoreManagerActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {

                    }
                });
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case R.id.imageView1:
                setAllClickImageViewfalse( );
                clickImageView1=true;
                getPhoto();
                break;
            case R.id.imageView2:
                setAllClickImageViewfalse( );
                clickImageView2=true;
                getPhoto();
                break;
            case R.id.imageView3:
                setAllClickImageViewfalse( );
                clickImageView3=true;
                getPhoto();
                break;
            case R.id.imageViewDel1:
                SweetDialogManager.getInstance().showDialogByWarmTitleText(this, "确定删除此图？", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                }, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        imageViewDel1.setVisibility(View.GONE);
                        imageView1.setImageResource(R.drawable.icon_default_camera);
                        imageView1.setPadding(AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30));
                        sweetAlertDialog.dismiss();
                    }
                });

                break;
            case R.id.imageViewDel2:
                SweetDialogManager.getInstance().showDialogByWarmTitleText(this, "确定删除此图？", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                }, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        imageViewDel2.setVisibility(View.GONE);
                        imageView2.setImageResource(R.drawable.icon_default_camera);
                        imageView2.setPadding(AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30));
                        sweetAlertDialog.dismiss();
                    }
                });
                break;
            case R.id.imageViewDel3:
                SweetDialogManager.getInstance().showDialogByWarmTitleText(this, "确定删除此图？", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                    }
                }, new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        imageViewDel3.setVisibility(View.GONE);
                        imageView3.setImageResource(R.drawable.icon_default_camera);
                        imageView3.setPadding(AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30),AbViewUtil.scaleValue(ZhiZhiCheckActivity.this,30));
                        sweetAlertDialog.dismiss();
                    }
                });
                break;
            case R.id.textChooseAddress:
                    if (regionBean != null) {
                        HideKeyboard();
                        selectAreaPopupWindow.showAtLocation(
                                ZhiZhiCheckActivity.this.findViewById(R.id.main), Gravity.BOTTOM
                                        | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }
                    else {
                       TaskGetRegionBean(false);
                    }
                break;
            case R.id.textViewSumit:
                //编辑的
                if (getIntent().getSerializableExtra(TagAddressEntity)!=null)
                {
                    TaskEdit(false);
                }else
                {
                    TaskSumit(false);
                }

                break;
            case R.id.textViewGoOnAdd:

                break;
        }
    }
    private void setAllClickImageViewfalse( ){
        clickImageView1=false;
        clickImageView2=false;
        clickImageView3=false;
    }
    private void getPhoto()
    {
        if (editDialog != null) {
            editDialog.show();
        }else{
        editDialog = EditDialog.create(this, new String[]{"拍照", "从手机相册选择",
        }, new EditDialogAction() {

            @Override
            public void clickItem4() {
                // nothing
            }

            @Override
            public void clickItem3() {

            }

            @Override
            public void clickItem2() {
                cameraUtil.openAlbum();
            }

            @Override
            public void clickItem1() {
                cameraUtil.openCamera();
            }
        });
            editDialog.show();
    }}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == CropImageActivity.TagFromClipActivity) {
            String filePath = data
                    .getStringExtra(CropImageActivity.TagCropBitmap);
            if (filePath != null) {
                if (clickImageView1) {
                    imageView1.setPadding(0,0,0,0);
                    imageViewDel1.setVisibility(View.VISIBLE);
                    file1=filePath;
                    App.displayImageHttpOrFile(filePath, imageView1, ImageUtil.OptionsNormalRadius18dp());
                }else if (clickImageView2) {
                    imageView2.setPadding(0,0,0,0);
                    imageViewDel2.setVisibility(View.VISIBLE);
                    file2=filePath;
                    App.displayImageHttpOrFile(filePath, imageView2, ImageUtil.OptionsNormalRadius18dp());
                }else if (clickImageView3) {
                    imageView3.setPadding(0,0,0,0);
                    imageViewDel3.setVisibility(View.VISIBLE);
                    file3=filePath;
                    App.displayImageHttpOrFile(filePath, imageView3, ImageUtil.OptionsNormalRadius18dp());
                }
            }
        } else {
            // 调用系统的图片或者拍照返回
            cameraUtil.getImgPath(requestCode, resultCode, data,
                    ImageDealTheard.getImageDealTheard(imageDealHandler));
        }

    }
    /**
     * 处理图片
     */
    private Handler imageDealHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int flag = msg.what;
            if (ImageDealTheard.THEARD_START == flag) {
                // dealImageDialog.show();
            } else if (ImageDealTheard.THEARD_END == flag) {
                String path = (String) msg.obj;
                Intent intent = new Intent(getActivity(),
                        CropImageActivity.class);
                intent.putExtra(CropImageActivity.TagCropBitmap, path);
                // 等比属性
                intent.putExtra(CropImageActivity.isAspectRatioXSeekTag,
                        true);
                startActivityForResult(intent,
                        CropImageActivity.TagFromClipActivity);
//
            }
        }
    };

    @Override
    public void getData(String ProviceName, String CityName, String DistrictName, String DistrictName_id) {
        areaId=DistrictName_id;
            textChooseAddress.setText(ProviceName+" "+CityName+""+DistrictName);
    }

    public void HideKeyboard()
    {
        //判断隐藏软键盘是否弹出
       // if(getWindow().getAttributes().softInputMode== WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED)
      //  {
        //隐藏软键盘
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
       // }
    }





}
